# coding=utf-8

import web

import settings
import utils
from controllers.admin.widgets import destination_dropdown

import models
from forms import hotel_setting_form, spider_form

render = settings.RENDER

class SpiderIndex(object):
    """
    蜘蛛管理
    """
    def GET(self, sid = '0'):
        f = spider_form()
        # 蜘蛛内码
        sid = utils.intval(sid)
        if sid > 0:
            spider = models.Spider.get(sid)
            if spider:
                f.name.value = spider.name
                f.partner_id.value = str(spider.partner_id)
                f.submit.attrs['html'] = u'修改：%s' % spider.name
        return self.render(f)

    def POST(self, sid = '0'):
        f = spider_form()
        # 蜘蛛内码
        sid = utils.intval(sid)
        if f.validates():
            if sid > 0:
                models.Spider.update(sid, f)
            else:
                models.Spider.add(f)

            return web.seeother('/spider')

        return self.render(f)

    def render(self, form):
        # 页码
        page = utils.intval(web.input().get('page', '0'))
        # 读取记录
        result = models.Spider.get_all(page * 20, 20)
        # 分页
        pager = utils.Pager(result.totalrecords, pageindex = page)
        return render.admin.spider.spider_index(form, result.lst, pager)

class HotelIndex(object):
    """酒店管理"""
    def GET(self):
        # 页码
        page = utils.intval(web.input().get('page', '0'))
        # 读取数据
        result = models.Hotel.get_all(page * 20, 20)
        # 分页
        pager = utils.Pager(result.totalrecords, pageindex = page)
        return render.admin.spider.hotel_index(result, pager, None)

class HotelAdd(object):
    """酒店添加/修改"""
    def GET(self, fid = '0'):
        f = hotel_setting_form()
        fid = utils.intval(fid)
        if fid > 0:
            hotel = models.Hotel.get(fid)
            if hotel:
                f.spider_id.value = hotel.id
                f.dest_id.value = hotel.dest_id
                f.stars.value = hotel.star
                f.url_regex.value = hotel.url_regex
                f.submit.attrs['html'] = u'修改酒店规则'
        return self.render(f)

    def POST(self, fid = '0'):
        f = hotel_setting_form()
        fid = utils.intval(fid)

        if f.validates():
            if fid > 0:
                if models.Hotel.update(fid, f):
                    return web.seeother('/spider/hotel/edit/%s?saved=true' % fid)
            else:
                fid = models.Hotel.add(f)
                if fid > 0:
                    return web.seeother('/spider/hotel/edit/%s?saved=true' % fid)

        return self.render(fid, f)

    def render(self, form):
        # 创建目的地选择控件
        dest_dropdown = destination_dropdown('dest_id'
                , val = form.dest_id.value
                , class_ = 'txt'
                , tabindex = 2)
        return render.admin.spider.hotel_add(form, dest_dropdown, saved = web.input().get('saved', None))
